package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.CateLog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Yanglinfengkk
 * 识图解析器进行拼串
 * prefix: classpath:/templates/
 * suffix: .html
 */
@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    /**
     * Redis分布式锁
     */
    @Autowired
    RedissonClient redisson;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 查询所有1级菜单信息
     *
     * @param model
     * @return
     */
    @GetMapping(value = {"/", "/index.html"})
    public String indexPage(Model model) {
        //TODO 1.查出所有1级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("cateorys", categoryEntities);
        return "index";
    }

    /**
     * 返回Map的原因返回的是一个Map是因为他是一个JSON对象,而Map就是一个Json对象
     * 查询2.3级菜单的所有信息
     *
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/index/catalog.json")
    public Map<String, List<CateLog2Vo>> getCatalogJson() {
        Map<String, List<CateLog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }

    /**
     * 实例demp
     * getLock()       可重入锁（Reentrant Lock）
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        //调用getLock获取一把锁,只要锁名一样那么就是同一把锁
        RLock lock = redisson.getLock("mylock");
        //加锁 阻塞式等待/直至获得锁再运行下面方法,默认加的锁都是30s时间
        //加锁的业务只要运行完成,就不会给当前锁续期,及时不手动解锁,锁也会在30s以后自动删除
        //锁的自动续机,如果业务超长,运行期间自动给锁续上新的30s,不用担心业务时间长,锁自动过期被删除的问题
        lock.lock();

        /*lock.lock(10, TimeUnit.SECONDS);*///10秒中自动解锁,自动解锁时间一定要大于业务执行的时间
        //问题:lock.lock(10, TimeUnit.SECONDS); 在锁时间到了以后不会自动续期
        //1.如果我们传递了锁的超时时间,就发送给Redis执行脚本,进行占锁,默认超时就是我们指定的时间
        /* 2.如果我们未指定传递锁的超时时间,就使用30000L(getLockWatchdogTimeout()看门狗默认时间),每隔10秒都会自动续期,续成30s
                只要占锁成功就会启动一个定时任务,[重新给锁设置过期时间就是看门狗的默认时间]
                   internalLockLeaseTime[看门狗时间] / 3L,10s
            */

        //最佳实战  推荐使用--->lock.lock(30, TimeUnit.SECONDS);省去了续期操作,手动解锁
        try {
            //+Thread.currentThread().getId() 获取线程ID号
            System.out.println("加锁成功,执行业务..." + Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (InterruptedException e) {

        } finally {
            //解锁
            System.out.println("释放锁..." + Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }

    /**
     * 保证一定能读到最新数据,修改期间,写锁是一个排他锁(互斥锁,独享锁),读锁是一个共享锁
     * 写锁存在,读锁就必须等待
     * 读 + 读    相当于无锁,并发读,只会在redis中记录好,所有当前的读锁,他们都会同时加锁成功
     * 写 + 读    等待写锁释放
     * 写 + 写    阻塞方式
     * 读 + 写    有读锁,写也需要等待
     * 只要有写的存在,都必须等待等待
     * @return
     */
    @GetMapping("/writer")
    @ResponseBody
    public String writerValue(){
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String s="";
        RLock rLock = lock.writeLock();
        try {
            //1.改数据加写锁,读数据加读锁
            rLock.lock();
            System.out.println("写锁加锁成功..." + Thread.currentThread().getId());
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            stringRedisTemplate.opsForValue().set("writerValue", s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
            System.out.println("写锁释放成功..." + Thread.currentThread().getId());
        }
        return s;
    }

    @GetMapping("/read")
    @ResponseBody
    public String readValue(){
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");

        /*ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();*/

        String s="";
        //加读锁
        RLock rLock = lock.readLock();
        rLock.lock();
        System.out.println("读锁加锁成功..." + Thread.currentThread().getId());
        try {
             s = stringRedisTemplate.opsForValue().get("writerValue");
            Thread.sleep(30000);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
            System.out.println("读锁加锁成功..." + Thread.currentThread().getId());
        }
        return s;
    }

    /**
     * 车库停车 3车位
     * 信号量（Semaphore）分布式限流操作
     * @return
     */
    @GetMapping("/part")
    @ResponseBody
    public String part() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
        //获取一个信号,获取一个值,占一个车位
        /*park.acquire();*/
        boolean b = park.tryAcquire();
        if(b){
            //执行业务
        }else{
            return "error";
        }
        return "OK-=>"+b;
    }

    @GetMapping("/go")
    @ResponseBody
    public String gogogo() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
        //示范一个信号,释放一个车位
        park.release();

      /*  Semaphore semaphore=new Semaphore(5);
        semaphore.release();    //-1
        semaphore.acquire();    //停车*/
        return "OK";
    }

    /**
     * 放假,锁门
     * 全校放假全部走完,锁校门
     *  闭锁(CountDownLatch)
     */
    @GetMapping("/CountDownLatch")
    @ResponseBody
    public String CountDownLatch() throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(5);
        //等待闭锁都完成
        door.await();
        return "放假了....";
    }

    @GetMapping("/go/{id}")
    @ResponseBody
    public String go(Long id){
        RCountDownLatch door = redisson.getCountDownLatch("door");
        //计数-1
        door.countDown();
        //CountDownLatch
        return id+"GO.....";
    }
}
